#include "shadersystem.h"

GLuint CShaderSystem::GetShader( int mode, std::string file )
{
	
	GLuint shader = glCreateShader( mode );
	
	std::string src = Util::GetFileContents( file );
	
	const char * c_src = src.c_str();
	
	glShaderSource( shader, 1, &c_src, NULL );
	
	glCompileShader( shader );
	
	GLint status;
	glGetShaderiv( shader, GL_COMPILE_STATUS, &status );
	
	if( status == GL_FALSE )
	{
		
		GLint log_len;
		glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &log_len );
		
		GLchar * c = new GLchar[log_len + 1];
		
		glGetShaderInfoLog( shader, log_len, NULL, c );
		
		char * output = new char[log_len + 255];
		
		sprintf( output, "Error loading shader '%s':\n%s", file.c_str(), c );
		
		Log::Debug( output );
		
		delete [] output;
		delete [] c;
		
	} else
	{
		
		Log::Debug( "Successfully loaded shader: " + file );
		
	}
	

	return shader;
	
}

void CShaderSystem::CreateProgram( std::string vertexfile, std::string fragfile )
{
	
	
	GLuint vshader = GetShader( GL_VERTEX_SHADER, vertexfile );
	GLuint fshader = GetShader( GL_FRAGMENT_SHADER, fragfile );
	
	GLuint program = glCreateProgram();
	
	glAttachShader( program, vshader );
	glAttachShader( program, fshader );
	
	glLinkProgram( program );
	
	glDetachShader( program, vshader );
	glDetachShader( program, fshader );
	
	glDeleteShader( vshader );
	glDeleteShader( fshader );
	
	m_vPrograms.push_back( program );
	
}

CShaderSystem::~CShaderSystem()
{
	
	for( int j = 0; j < m_vPrograms.size(); j++ )
	{
		
		glDeleteProgram( m_vPrograms[j] );
		
	}
	
}